package com.hbter630.change.controller;

import cn.hutool.core.lang.UUID;
import com.hbter630.change.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Title: fileUploadController
 * @Author 笑霸fianl
 * @Package com.hbter630.change.controller
 * @Date 2023/5/28 10:49
 * @描述: 文件上传
 */
@Slf4j
@ResponseBody
@RestController
@RequestMapping("/common")
@Api(tags = "文件上传与下载")
public class fileUploadController {
    //读取yml配置文件的位置
    @Value("${myfile.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation(notes = "文件上传",value = "文件上传", httpMethod = "POST", response = Result.class)
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){

        //原始文件名
        final String originalFilename = file.getOriginalFilename();
        //获取 .jpg文件后缀
        final String substring = originalFilename.substring(originalFilename.lastIndexOf("."));

        //随机名
        String uuid=UUID.randomUUID().toString() +substring;
        //创建一个目录
        File file1 = new File(basePath);
        //判断目录是否存在
        if(!file1.exists()){
            //目录不存在就创建
            file1.mkdirs();
        }
        //将文件转存
        try{
            file.transferTo(new File(basePath+uuid));
        }catch (IOException e){

        }
        return Result.ok().addMessage(uuid);//应该返回文件名 文件名前端或做相关的关联
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */

    @ApiOperation(notes = "文件下载",value = "文件下载", httpMethod = "GET", response = Result.class)
    @GetMapping("/download/{name}")
    public void download(@PathVariable("name") String name, HttpServletResponse response) throws IOException {


        log.info("\n ====== \n");
        System.out.println(name);
        //输入流读取文件内容
        final FileInputStream fileInputStream
                = new FileInputStream(new File(basePath+name));


        //输出流将文件写回浏览器
        final ServletOutputStream outputStream = response.getOutputStream();

        int len=0;
        byte[] bytes=new byte[1024];
        while ((len=fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        response.setContentType("image/jpg");

        //关闭流
        outputStream.close();
        fileInputStream.close();

    }



}
